package com.ctshk.rpc.finance.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.constant.RedisConstants;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.common.utils.SnowflakeIdWorker;
import com.ctshk.rpc.finance.dto.customer.CustomDataDetailCountDTO;
import com.ctshk.rpc.finance.dto.customer.CustomerDataDetailDTO;
import com.ctshk.rpc.finance.dto.customer.CustomerDataListDTO;
import com.ctshk.rpc.finance.entity.FinanceCustomerData;
import com.ctshk.rpc.finance.entity.FinanceCustomerDataDetail;
import com.ctshk.rpc.finance.json.ClientInfoJson;
import com.ctshk.rpc.finance.json.FileJson;
import com.ctshk.rpc.finance.mapper.FinanceCustomerDataDetailMapper;
import com.ctshk.rpc.finance.mapper.FinanceCustomerDataMapper;
import com.ctshk.rpc.finance.req.customer.CustomDataDetailReq;
import com.ctshk.rpc.finance.req.customer.CustomerDataAddReq;
import com.ctshk.rpc.finance.req.customer.CustomerDataIdReq;
import com.ctshk.rpc.finance.req.customer.CustomerDataListReq;
import com.ctshk.rpc.finance.service.IFinanceCustomerDataService;
import com.ctshk.rpc.system.dto.UserDTO;
import com.ctshk.rpc.system.service.ISysUserService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 客商期初 服务实现类
 * </p>
 *
 * @author 叶冠峰
 * @since 2021-04-06
 */
@DubboService
public class FinanceCustomerDataServiceImpl extends ServiceImpl<FinanceCustomerDataMapper, FinanceCustomerData> implements IFinanceCustomerDataService {

    @Autowired
    private FinanceCustomerDataMapper customerDataMapper;
    @Autowired
    private FinanceCustomerDataDetailMapper customerDataDetailMapper;

    /*@Autowired
    private RedisTemplate<String, Object> redisTemplate;*/

    @DubboReference
    private ISysUserService sysUserService;



    /**
     * 列表
     *
     * @param req
     * @return
     */
    @Override
    public Result<PageResponse<CustomerDataListDTO>> list(CustomerDataListReq req) {
        Page<FinanceCustomerData> iPage = new Page<>(req.getPageNo(), req.getPageSize());
        QueryWrapper<FinanceCustomerData> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(req.getClientName()),"client_name",req.getClientName());
        queryWrapper.like(StringUtils.isNotBlank(req.getContacts()),"contacts",req.getContacts());
        queryWrapper.between(req.getCreateTimeBegin() != null && req.getCreateTimeEnd() != null,"gmt_create",req.getCreateTimeBegin(),req.getCreateTimeEnd());
        queryWrapper.orderByDesc("gmt_create");
        Page<FinanceCustomerData> page = customerDataMapper.selectPage(iPage, queryWrapper);
        if (CollectionUtils.isEmpty(page.getRecords())) {
            return Result.success(PageResponse.empty(page.getCurrent()));
        }
        List<CustomerDataListDTO> list = new ArrayList<>();
        page.getRecords().forEach(data -> {
            CustomerDataListDTO dto = EntityUtil.copy(data,CustomerDataListDTO.class);
            //申请人
//            UserDTO userDto = (UserDTO) redisTemplate.opsForValue().get(RedisConstants.ACCOUNT_QUERY_KEY + data.getCreateId());
            UserDTO userDto = sysUserService.queryCacheUser(data.getCreateId());
            if (userDto != null){
                dto.setApplyUserDept(userDto.getDept());
                dto.setApplyUserName(userDto.getFullName());
            }
            //期初币种统计
            List<CustomDataDetailCountDTO> detailList = customerDataDetailMapper.queryListByCustom(data.getId());
            if (detailList != null && detailList.size() > 0){
                dto.setDetailList(detailList);
            }
            list.add(dto);
        });
        PageResponse<CustomerDataListDTO> result = new PageResponse<>(
                list,
                page.getCurrent() == 1,
                page.getTotal() <= (page.getCurrent() * page.getSize()),
                page.getTotal(),
                page.getCurrent(),
                page.getSize());
        return Result.success(result);
    }

    /**
     * 新增
     *
     * @param req
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result add(CustomerDataAddReq req) {
        //新增期初
        FinanceCustomerData data = new FinanceCustomerData();
        data.setId(SnowflakeIdWorker.nextId());
        ClientInfoJson clientInfoJson = req.getClientInfoJson();
        data.setClientId(clientInfoJson.getAccountId());
        data.setClientName(clientInfoJson.getAccountName());
        data.setClientInfoJson(JSON.toJSONString(clientInfoJson));
        data.setContacts(clientInfoJson.getContactName());
        if (req.getFilesJsonList().size() == 0){
            throw new BusinessException(SystemError.SYS_428,"附件");
        }
        data.setFilesJson(JSON.toJSONString(req.getFilesJsonList()));
        List<CustomDataDetailReq> detailReqList = req.getDetailReqList();
        if (detailReqList.size() == 0){
            throw new BusinessException(SystemError.SYS_428,"明细列表");
        }
        data.setCreateId(req.getUserId());
        data.setIsDeleted(0);
        boolean save = save(data);
        //批量新增明细
        List<FinanceCustomerDataDetail> detailList = new ArrayList<>();
        detailReqList.forEach(detailReq -> {
            FinanceCustomerDataDetail detail = EntityUtil.copy(detailReq,FinanceCustomerDataDetail.class);
            detail.setId(SnowflakeIdWorker.nextId());
            detail.setDataId(data.getId());
            detail.setCreateId(req.getUserId());
            detail.setIsDeleted(0);
            detailList.add(detail);
        });
        Integer batch = customerDataDetailMapper.insertBatchSomeColumn(detailList);
        if (!save || batch < detailList.size()){
            throw new BusinessException(SystemError.SYS_437);
        }
        return Result.success(data.getId());
    }

    /**
     * 详情
     *
     * @param req
     * @return
     */
    @Override
    public Result<CustomerDataDetailDTO> detail(CustomerDataIdReq req) {
        FinanceCustomerData data = getById(req.getId());
        if (data == null || Objects.equals(data.getIsDeleted(),1)){
            throw new BusinessException(SystemError.FINANCE_BILL_17022);
        }
        CustomerDataDetailDTO dto = EntityUtil.copy(data,CustomerDataDetailDTO.class);
        //客户信息
        if (StringUtils.isNotBlank(data.getClientInfoJson())){
            dto.setClientInfoJson(JSON.parseObject(data.getClientInfoJson(),ClientInfoJson.class));
        }
        //附件
        if (StringUtils.isNotBlank(data.getFilesJson())){
            dto.setFilesJson(JSON.parseArray(data.getFilesJson(), FileJson.class));
        }
        //申请人
//        UserDTO userDto = (UserDTO) redisTemplate.opsForValue().get(RedisConstants.ACCOUNT_QUERY_KEY + data.getCreateId());
        UserDTO userDto = sysUserService.queryCacheUser(data.getCreateId());
        if (userDto != null){
            dto.setApplyUserDept(userDto.getDept());
            dto.setApplyUserName(userDto.getFullName());
        }
        //明细列表
        QueryWrapper<FinanceCustomerDataDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("data_id",data.getId());
        queryWrapper.eq("is_deleted",0);
        List<FinanceCustomerDataDetail> detailList = customerDataDetailMapper.selectList(queryWrapper);
        List<CustomDataDetailReq> customDataDetailReqs = EntityUtil.copyList(detailList, CustomDataDetailReq.class);
        dto.setDetailReqList(customDataDetailReqs);
        return Result.success(dto);
    }


}
